<?php
/**
 * Controller_Route
 * 
 * 作者:  姚刚 (yaogang@the9sense.com)
 * 创建时间: 2011-02-24 00:16:32
 * 修改记录: 
 * 
 * $Id: Route.php 18 2011-04-17 12:50:07Z coosuu $
 */

class Controller_Route {

    private static $_instance = null;

    private $_controllerName;

    private $_actionName;

    public function __construct() {

        $this->_route();
    }

    public static function &getInstance() {

        if (!self::$_instance) {
            self::$_instance = new self;
        }
        return self::$_instance;
    }

    public function getControllerName() {

        return $this->_controllerName;
    }

    public function getActionName() {

        return $this->_actionName;
    }

    private function _route() {

        $uri = $_SERVER['REQUEST_URI'];
        if (!$uri) {
            throw new Controller_Exception('Route need $_SERVER["REQUEST_URI"] support');
        }

        $pos = strpos($uri, '?');
        if ($pos !== false) {
            $uri = substr($uri, 0, $pos);
        }

        $uri = trim($uri, '/');
        if (!$uri) {
            $this->_controllerName = APP_NAME . '_Controller_Default';
            $this->_actionName = 'indexAction';
        } else {

            $uriArr = explode('/', $uri);
            if (count($uriArr) >= 2) {
                $uriArr = array_slice($uriArr, 0, 2);
            } else {
                $uriArr[] = null;
            }

            list($controllerName, $actionName) = $uriArr;
            if (!$controllerName) {
                $this->_controllerName = APP_NAME . '_Controller_Default';
            } else {
                $this->_controllerName = APP_NAME . '_Controller_' . ucwords(strtolower($controllerName));
            }

            if (!$actionName) {
                $this->_actionName = 'indexAction';
            } else {
                $this->_actionName = $actionName . 'Action';
            }
        }

        Bootstrap::setEnv('controllerName', $this->_controllerName);
        Bootstrap::setEnv('actionName', $this->_actionName);
    }
}
